package com.example.messengerapp.ui

import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.messengerapp.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import java.util.UUID

class ChangeAvatarActivity : AppCompatActivity() {

    private lateinit var avatarImageView: ImageView
    private lateinit var selectImageButton: Button
    private lateinit var applyImageButton: Button

    private val PICK_IMAGE_REQUEST = 1
    private var imageUri: Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_change_avatar_activity)

        avatarImageView = findViewById(R.id.avatarImageView)
        selectImageButton = findViewById(R.id.selectImageButton)
        applyImageButton = findViewById(R.id.applyImageButton)

        selectImageButton.setOnClickListener {
            openFileChooser()
        }

        applyImageButton.setOnClickListener {
            uploadImageToFirebase()
        }
    }

    private fun openFileChooser() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        startActivityForResult(intent, PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.data != null) {
            imageUri = data.data
            avatarImageView.setImageURI(imageUri)
        }
    }

    private fun uploadImageToFirebase() {
        if (imageUri != null) {
            val progressDialog = ProgressDialog(this)
            progressDialog.setTitle("Uploading...")
            progressDialog.show()

            val storageReference = FirebaseStorage.getInstance().getReference("avatars/${UUID.randomUUID()}.jpg")

            storageReference.putFile(imageUri!!)
                .addOnSuccessListener { taskSnapshot ->
                    storageReference.downloadUrl.addOnSuccessListener { uri ->
                        val imageUrl = uri.toString()
                        saveImageUrlToDatabase(imageUrl)
                        progressDialog.dismiss()
                        Toast.makeText(this, "Image Uploaded Successfully", Toast.LENGTH_SHORT).show()
                    }
                }
                .addOnFailureListener {
                    progressDialog.dismiss()
                    Toast.makeText(this, "Failed to Upload Image", Toast.LENGTH_SHORT).show()
                }
                .addOnProgressListener { taskSnapshot ->
                    val progress = (100.0 * taskSnapshot.bytesTransferred / taskSnapshot.totalByteCount)
                    progressDialog.setMessage("Uploaded ${progress.toInt()}%")
                }
        } else {
            Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show()
        }
    }

    private fun saveImageUrlToDatabase(imageUrl: String) {
        val databaseReference = FirebaseDatabase.getInstance().getReference("users")
        val userId = FirebaseAuth.getInstance().currentUser?.uid
        if (userId != null) {
            databaseReference.child(userId).child("avatarUrl").setValue(imageUrl)
        }
    }
}
